import * as api from '../../utils/api.js';
const DatePickerUtil = require('../../utils/DatePicker')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    brandList: [],
    brnadObj:{},
    brand_index: 0,
    modelList: [],
    modelObj:{},
    model_index: 0,
    doorTypeList: ['木门','钢门'],
    lockModelList: ['2.4*24','3.0*24','4.0*38.8','其他'],
    lockType:0,
    disabled:true,
    doorType: 0,
    brand_id:0,
    model_id:0,
    installInfo:{num:1,lock_model:'2.4*24'},
    region: ['', '', ''],
    // 选择地区的中心经纬度
    tempLatLng: {
      lat: '',
      lng: ''
    },
    time:'选择预约时间',
    multiArray:[],//piker的item项
    multiIndex:[],//当前选择列的下标
    year:'',//选择的年
    month:'',//选择的月
    day:'',//选择的日
    hour:'',//选择的时
    minute:''//选择的分
  },
  bindBrandChange(e) {
    const that = this
    const brand_index = e.detail.value
    const brand_id = that.data.brnadObj[brand_index].id
    that.getModelList(brand_id)
    that.setData({
      brand_index,
      brand_id
    })
  },
  bindModelChange(e){
    const that = this
    const model_index = e.detail.value
    const model_id = that.data.modelObj[model_index].id
    this.setData({
      model_id,model_index
    })
  },
  bindDoorTypeChange(e) {
    
    this.setData({
      doorType: e.detail.value
    })
  },
  bindLockModelChange(e) {
    var lockModelList=this.data.lockModelList
    var installInfo = this.data.installInfo
    installInfo.lock_model = lockModelList[e.detail.value]
    if(e.detail.value == 3){
      this.setData({
        installInfo: installInfo,
        lockType:e.detail.value,
        disabled:false
      })
    }else{
      this.setData({
        installInfo: installInfo,
        lockType:e.detail.value,
        disabled:true
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getBrandList()
  },

  getBrandList(){
    const that = this
    api.installBrandList()
      .then(res => {
        const brnadObj = res.data
        const brandList = []
        let brand_id = 0
        brnadObj.forEach(element => {
          brandList.push(element.name)
        });
        brand_id = brnadObj[0].id
        that.setData({
          brandList,
          brnadObj,
          brand_id
        })
        that.getModelList(brand_id)
      }).catch(err => console.log(err))
  },

  getModelList(brand_id = 1){
    const that = this
    api.installModelList(brand_id)
      .then(res => {
        const modelObj = res.data
        const modelList = []
        let model_id = 0
        modelObj.forEach(element => {
          modelList.push(element.name)
        });
        model_id = modelObj[0].id
        that.setData({
          modelList,
          modelObj,
          model_id
        })
      }).catch(err => console.log(err))
  },

  inputEvent(e) {
    const name = e.currentTarget.dataset.name
    const value = e.detail.value.trim()
    let installInfo = this.data.installInfo
    installInfo[name] = value
    this.setData({
      installInfo
    })
  },

  bindRegionChange(e) {
    const region = e.detail.value
    let city_name = region[1]
    let area_name = region[2]
    this.setData({
      region
    })
    const code = e.detail.postcode
    this.getAreaByName(city_name,area_name)
  },

  getAreaByName(city_name,area_name) {
    const that = this
    api.getAreaByName(city_name,area_name)
      .then(res => {
        console.log(res)
        const region = res.data
        let installInfo = that.data.installInfo
        let tempLatLng = that.data.tempLatLng
        installInfo.province_id = region.province.id
        installInfo.city_id = region.city.id
        installInfo.area_id = region.area.id
        tempLatLng.lat = region.area.lat
        tempLatLng.lng = region.area.lng
        that.setData({
          installInfo,
          tempLatLng
        })
      }).catch(err => console.log(err))
  },

  chooseLocation() {
    const that = this
    let installInfo = that.data.installInfo
    let tempLatLng = that.data.tempLatLng
    const latitude = installInfo.latitude ? installInfo.latitude : (tempLatLng.lat ? tempLatLng.lat : '')
    const longitude = installInfo.longitude ? installInfo.longitude : (tempLatLng.lng ? tempLatLng.lng : '')
    let options = {}
    if (latitude) options.latitude = latitude
    if (longitude) options.longitude = longitude
    options.success = function (res) {
      installInfo.latitude = res.latitude.toFixed(5)
      installInfo.longitude = res.longitude.toFixed(5)
      installInfo.address = res.address
      that.setData({
        installInfo
      })
    } 
    options.fail = function (err) {
      console.log(err)
    }
    wx.chooseLocation(options)
  },
  bindMultiPickerChange: function(e) { //时间日期picker选择改变后，点击确定 
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      multiIndex: e.detail.value
    })
    const index = this.data.multiIndex; // 当前选择列的下标
    const year = this.data.multiArray[0][index[0]];
    const month = this.data.multiArray[1][index[1]];
    const day = this.data.multiArray[2][index[2]];
    const hour = this.data.multiArray[3][index[3]];
    const minute = this.data.multiArray[4][index[4]];
    this.setData({
      time: year+ month+ day + ' ' + hour.replace('时','')+':'+minute.replace('分',''),
      year:year, //记录选择的年
      month:month, //记录选择的月
      day:day, //记录选择的日
      hour:hour, //记录选择的时
      minute:minute, //记录选择的分 
    })
  }, 
  bindMultiPickerColumnChange: function(e) { //监听picker的滚动事件
  
    // console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    
    let getCurrentDate = DatePickerUtil.getCurrentDate();//获取现在时间  
    let currentYear = parseInt(getCurrentDate.substring(0,4)); 
    let currentMonth = parseInt(getCurrentDate.substring(5,7)); 
    let currentDay = parseInt(getCurrentDate.substring(8,10)); 
    let currentHour = parseInt(getCurrentDate.substring(11,13));  
    let currentMinute = parseInt(getCurrentDate.substring(14,16)); 
    
    if (e.detail.column == 0) {//修改年份列 
     
      let yearSelected = parseInt(this.data.multiArray[e.detail.column][e.detail.value]);//当前选择的年份
 
      this.setData({ 
        multiIndex:[0,0,0,0,0] ,//设置pickerIndex
        year:yearSelected //当前选择的年份
      });
      
      if(yearSelected == currentYear){//当前选择的年份==当前年份  
        var loadPickerData=DatePickerUtil.loadPickerData();
        
        this.setData({
          multiArray:loadPickerData,//picker数组赋值
          multiIndex:[0,0,0,0,0] //设置pickerIndex
        });
        
      }else{  // 选择的年份！=当前年份 
      
        // 处理月份
        let monthArr=DatePickerUtil.loadMonths(1,12)
        // 处理日期
        let dayArr=DatePickerUtil.loadDays(currentYear,currentMonth,1) 
        // 处理hour
        let  hourArr=DatePickerUtil.loadHours(0,24); 
        // 处理minute
        let  minuteArr=DatePickerUtil.loadMinutes(0,60)
         
        // 给每列赋值回去
        this.setData({
          ['multiArray[1]']: monthArr,
          ['multiArray[2]']: dayArr,
          ['multiArray[3]']: hourArr,
          ['multiArray[4]']: minuteArr
        });
      }
    }
    if (e.detail.column == 1) {//修改月份列
      let mon = parseInt(this.data.multiArray[e.detail.column][e.detail.value]); //当前选择的月份
      this.setData({
        month:mon  // 记录当前列
      })
      
      if(mon==currentMonth){//选择的月份==当前月份 
        if(this.data.year==currentYear){  
        
          // 处理日期
          let dayArr=DatePickerUtil.loadDays(currentYear,mon,currentDay) 
          // 处理hour
          let  hourArr=DatePickerUtil.loadHours(currentHour,24); 
          // 处理minute
          let  minuteArr=DatePickerUtil.loadMinutes(currentMinute,60)

          this.setData({ 
            ['multiArray[2]']:dayArr,
            ['multiArray[3]']: hourArr,
            ['multiArray[4]']: minuteArr
          })
        }else{ 
          // 处理日期
          let dayArr=DatePickerUtil.loadDays(currentYear,mon,1) 
          // 处理hour
          let  hourArr=DatePickerUtil.loadHours(0,24); 
          // 处理minute
          let  minuteArr=DatePickerUtil.loadMinutes(0,60)
          
          this.setData({
            ['multiArray[2]']:dayArr,
            ['multiArray[3]']: hourArr,
            ['multiArray[4]']: minuteArr
          });
        } 
      }else{  // 选择的月份！=当前月份 
         // 处理日期
         let dayArr = DatePickerUtil.loadDays(currentYear,mon,1) // 传入当前年份，当前选择的月份去计算日
         // 处理hour
         let  hourArr = DatePickerUtil.loadHours(0,24); 
         // 处理minute
         let  minuteArr = DatePickerUtil.loadMinutes(0,60)
         
       	 this.setData({
           ['multiArray[2]']:dayArr,
           ['multiArray[3]']: hourArr,
           ['multiArray[4]']: minuteArr
         });
      } 
    } 
    if(e.detail.column == 2) {//修改日
      let dd = parseInt(this.data.multiArray[e.detail.column][e.detail.value]);//当前选择的日
      this.setData({
        day:dd
      })
      if(dd==currentDay){//选择的日==当前日
        if(this.data.year==currentYear&&this.data.month==currentMonth){//选择的是今天 
        
         // 处理hour
         let  hourArr=DatePickerUtil.loadHours(currentHour,24); 
         // 处理minute
         let  minuteArr=DatePickerUtil.loadMinutes(currentMinute,60)
         
         this.setData({
            ['multiArray[3]']: hourArr,
            ['multiArray[4]']: minuteArr
         });
         
        }else{ //选择的不是今天 
          // 处理hour
          let  hourArr=DatePickerUtil.loadHours(0,24); 
          // 处理minute
          let  minuteArr=DatePickerUtil.loadMinutes(0,60)
          
          this.setData({
             ['multiArray[3]']: hourArr,
             ['multiArray[4]']: minuteArr
          });
        }
      }else{  // 选择的日！=当前日 
       // 处理hour
       let  hourArr=DatePickerUtil.loadHours(0,24); 
       // 处理minute
       let  minuteArr=DatePickerUtil.loadMinutes(0,60)
       
       this.setData({
         ['multiArray[3]']: hourArr,
         ['multiArray[4]']: minuteArr
       });
      }
    } 
    if(e.detail.column == 3) {//修改时
      let hh = parseInt(this.data.multiArray[e.detail.column][e.detail.value]); //当前选择的时
      this.setData({
        hour:hh
      })
      if(hh==currentHour){//选择的时==当前时 
        if(this.data.year==currentYear&&this.data.month==currentMonth&&this.data.month==currentMonth){   // 选择的是今天
          
          // 处理minute
            let  minuteArr=DatePickerUtil.loadMinutes(currentMinute,60)
            this.setData({ 
              ['multiArray[4]']: minuteArr
            });
        }else{ // 选择的不是今天
        
          // 处理minute
          let  minuteArr=DatePickerUtil.loadMinutes(0,60)
          this.setData({ 
            ['multiArray[4]']: minuteArr
          });
        } 
      }else{//选择的时！=当前时 
        // 处理minute
        let  minuteArr=DatePickerUtil.loadMinutes(0,60)
        this.setData({ 
          ['multiArray[4]']: minuteArr
        });
      }
    }
    var data = {
      multiArray: this.data.multiArray,
      multiIndex: this.data.multiIndex
    };

    // console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    data.multiIndex[e.detail.column] = e.detail.value; //将值赋回去
    
    this.setData(data);  //将值赋回去
  },

  checkInstallInfo(installInfo){
    if(!installInfo.contacts) {
      wx.showToast({
        title: '请填写联系人',
        icon: 'none'
      })
      return new Promise((resolve, reject) => resolve(false));
    }
    if(!installInfo.contact_number) {
      wx.showToast({
        title: '请填写手机号',
        icon: 'none'
      })
      return new Promise((resolve, reject) => resolve(false));
    }
    if(!installInfo.province_id) {
      wx.showToast({
        title: '请选择城市',
        icon: 'none'
      })
      return new Promise((resolve, reject) => resolve(false));
    }
    if(!installInfo.latitude) {
      wx.showToast({
        title: '请选择位置',
        icon: 'none'
      })
      return new Promise((resolve, reject) => resolve(false));
    }
    if(!installInfo.address) {
      wx.showToast({
        title: '请填写地址',
        icon: 'none'
      })
      return new Promise((resolve, reject) => resolve(false));
    }
    return new Promise((resolve, reject) => resolve(true));
  },

  submit(){
    const that = this
    let installInfo = that.data.installInfo
    that.checkInstallInfo(installInfo).then(res => {
      if(res) {
        api.getUserId(installInfo.contact_number)
          .then(res => {
            const customer_user_id = res.data
            const brand_id = that.data.brand_id
            const model_id = that.data.model_id
            const door_type = that.data.doorType
            const num = installInfo.num
            const contacts = installInfo.contacts
            const contact_number = installInfo.contact_number
            const province_id = installInfo.province_id
            const city_id = installInfo.city_id
            const area_id = installInfo.area_id
            const address = installInfo.address
            const latitude = installInfo.latitude
            const longitude = installInfo.longitude
            const install_time = that.data.time.replace('年', '-').replace('月', '-').replace('日', ' ')
            const remarks = installInfo.remarks
            const lock_model = installInfo.lock_model
            api.businessCreateInstallOrder(customer_user_id,brand_id,model_id,door_type,num,contacts,contact_number,province_id,city_id,area_id,address,latitude,longitude,install_time,remarks,lock_model)
              .then(res => {
                if(res.code == 1) {
                  wx.showToast({
                    title: '添加成功,请耐心等待后台派单',
                    icon: 'none'
                  })
                  setTimeout(function(){
                    wx.navigateTo({
                      url: '/pages/business/installOrderList',
                    })
                  },1500)
                }
              }).catch(err => {
                wx.showToast({
                  title: err.msg,
                  icon: 'none',
                  duration: 3000,
                })
              })
          }).catch(err => {
            wx.showToast({
              title: err.msg,
              icon: 'none',
              duration: 3000,
            })
          })
      }
    }).catch(err => console.log(err))
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //获取 DatePickerUtil 工具下的方法
    var  loadPickerData=DatePickerUtil.loadPickerData()
    var  getCurrentDate=DatePickerUtil.getCurrentDate()
    var  GetMultiIndex=DatePickerUtil.GetMultiIndex() 
    
    //这里写的是为了记录当前时间
    let year=parseInt(getCurrentDate.substring(0,4)); 
    let month=parseInt(getCurrentDate.substring(5,7)); 
    let day=parseInt(getCurrentDate.substring(8,10)); 
    let hour=parseInt(getCurrentDate.substring(11,13));   
    let minute=parseInt(getCurrentDate.substring(14,16)); 
    
    this.setData({  
      multiArray:loadPickerData,//picker数组赋值，格式 [years, months, days, hours, minutes]
      multiIndex:GetMultiIndex,//设置pickerIndex，[0,0,0,0,0]
      time:getCurrentDate, //设置当前时间 ，currentYears+'-'+mm+'-'+dd+' '+hh+':'+min
      year:year,//记录选择的年
      month:month,//记录选择的月
      day:day,//记录选择的日
      hour:hour,//记录选择的时
      minute:minute,//记录选择的分 
    });   
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})